package com.tian.controller;

import com.tian.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(@RequestParam("account") String account, @RequestParam("password") String password, Model model, HttpSession session1){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //获取登录令牌
        UsernamePasswordToken token=new UsernamePasswordToken(account,password);
        try {
            String url="";
            //登录跳转shiro过滤处理
            subject.login(token);
          /*  if(subject.hasRole("amdin")){
                return "admin/admin";
            }*/
            //判断用户角色，进行制定跳转
            Session session=subject.getSession();
            User user= (User) session.getAttribute("user");
            if(user.getRole().equals("admin")){
                session1.setAttribute("admin",user);
                url="AdminMain";
            }
            if(user.getRole().equals("user")){
                session1.setAttribute("visitor",user);
                url="UserMain";
            }
            return url;
        }catch (UnknownAccountException e){
            model.addAttribute("msg","账号错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
    @RequestMapping("/logout")
    public String logout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
